﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace TcpServer监听所有网卡
{
    class Program
    {


        static void Main(string[] args)
        {
            //IPAddress.Any为所有网卡，
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8088);
            //创建listens是传入的套接字。
            Socket listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.NoDelay = true;
            //绑定端口
            listenSocket.Bind(localEndPoint);
            //挂起的连接队列的最大长度。
            listenSocket.Listen(1000);
            Console.WriteLine("Server Accept...");
            while (true)
            {
                Socket clientSocket = listenSocket.Accept();
                Console.WriteLine(clientSocket.RemoteEndPoint.ToString() + "Connet...");
                Thread th = new Thread(DevThread);
                th.IsBackground = true;
                th.Start(clientSocket);
            }
        }

        static public void DevThread(object obj)
        {
            Socket devSock = (Socket)obj;
            Console.WriteLine(devSock.RemoteEndPoint.ToString() + " Thread Start!");
            byte[] recBuf = new byte[8192];

            while(true)
            {
                int n = devSock.Receive(recBuf);
                if(n <= 0)
                {
                    return;
                }
                string msg = System.Text.Encoding.ASCII.GetString(recBuf);
                //Debug.Print(msg);
                Console.WriteLine(msg);
                byte[] sendBuf = System.Text.Encoding.ASCII.GetBytes(msg);
                devSock.Send(sendBuf);
            }
        }
    }
}
